package edu.cuit.avatar.concurrent;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;

/**
 * java集合框架提供了ArrayBlockingQueue、LinkedBlockingQueue、PriorityBlockingQueue来支持阻塞队列
 * 阻塞队列：试图向满队列添加元素或者从空队列删除元素会导致线程阻塞
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/17 10:13
 */
public class ProducerConsumerUsingBlockingQueue {
    private static ArrayBlockingQueue<Integer> buffer = new ArrayBlockingQueue<>(5);

    private static class ProducerTask implements Runnable{
        @Override
        public void run() {
            try {
                int i = 1;
                while(true){
                    System.out.println("Producer writes " + i);
                    //向阻塞队列写入数据
                    buffer.put(i++);
                    Thread.sleep(5);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static class ConsumerTask implements Runnable{
        @Override
        public void run() {
            try {
                while(true){
                    System.out.println("Consumer reads " + buffer.take());
                    Thread.sleep(5);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        var  executor = Executors.newFixedThreadPool(2);

        executor.execute(new ConsumerTask());
        executor.execute(new ProducerTask());

        executor.shutdown();
    }
}
